package com.cwx.service;

import com.cwx.NotFoundException;
import com.cwx.dao.TypeRepository;
import com.cwx.pojo.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService{

    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    //添加一个
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    //查找一个
    public Type getType(String name) {
        return typeRepository.findByName(name);
    }

    //通过id查找类别
    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findById(id).orElse(null);
    }

    @Transactional
    @Override
    //查找多个  分页
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    @Transactional
    //修改一个分类
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.getById(id);

        if (t == null){
            throw new NotFoundException("不存在此人");
        }else {
            BeanUtils.copyProperties(type,t);  //前面的赋值给后面的、
            return typeRepository.save(t);
        }
    }

    @Transactional
    @Override
    //删除一个分类
    public void deletedType(Long id) {
        typeRepository.deleteById(id);
    }

    @Transactional
    @Override
    public Type getTypeById(Long id) {
        return typeRepository.getById(id);
    }

    @Transactional
    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }

    //根据分类所拥有的博客数量 获取前六个类型的分类
    @Override
    public List<Type> listTypeTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"blogs.size");
        Pageable pageable = PageRequest.of(0,size,sort);
        return typeRepository.findTop(pageable);
    }
}
